package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.recyclerview.LRecyclerView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.adapter.rv.CommonAdapter;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.IsFastClickUtil;
import cn.mumzone.basic.util.ItemClickSupport;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.MoneyFormatUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.ReturnEntity;
import cn.mumzone.pos.model.ReturnGoodsEntity;
import cn.mumzone.pos.model.SunMiPayResponse;
import cn.mumzone.pos.presenter.BillReturnNewPresenter;
import cn.mumzone.pos.presenter.contract.BillReturnContract;
import cn.mumzone.pos.ui.adapter.ADA_BillReturnCartStepOne;
import cn.mumzone.pos.ui.adapter.ADA_BillReturnCartStepTwo;
import cn.mumzone.pos.ui.adapter.ADA_BillReturnGoodsList;
import cn.mumzone.pos.ui.adapter.ADA_ReturnMoneyDetail;
import cn.mumzone.pos.ui.widgets.StepView;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.util.BillUtil;
import cn.mumzone.pos.util.CloneUtil;
import cn.mumzone.pos.util.GoodsUtil;
import cn.mumzone.pos.util.print.PrintPayTypeEntity;
import cn.mumzone.pos.util.returngoods.AddReturnCartUtil;
import cn.mumzone.pos.util.returngoods.ReturnUtil;
import cn.mumzone.pos.util.print.PrinterService;

/**
 * Created by JoeLjt on 2019/7/9.
 * Email: lijiateng1219@gmail.com
 * Description:
 * 商品退货，弹窗样式，分为一、二、三步骤
 */

public class ACT_BillReturn extends BaseActivity<BillReturnNewPresenter> implements BillReturnContract.View {

    /**
     * 退货商品列表
     */
    private final LinkedList<ReturnGoodsEntity> mReturnCartList = new LinkedList<>();

    /**
     * 存储退货步骤的 layout，以 layoutId 为 key
     */
    private final SparseArray<View> mReturnStepList = new SparseArray<>();

    private static final String KEY_ORDER_CODE = "orderCode";
    private static final String KEY_IS_FROM_LIST = "isFromList";
    private static final String KEY_SALE_ID = "saleId";
    private static final String KEY_ORDER_TYPE = "orderType";

    public static final int REQUEST_CODE_FOR_RETURN = 100;

    @BindView(R.id.ll_root_return)
    LinearLayout llRootReturn;
    @BindView(R.id.iv_finish)
    ImageView ivFinish;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_bill_list)
    LRecyclerView rvBillList;

    @BindView(R.id.ll_return_left)
    LinearLayout llLeft;
    @BindView(R.id.et_search_goods)
    EditText etSearchGoods;
    @BindView(R.id.et_scan)
    EditText etScan;
    @BindView(R.id.rb_search)
    RadioButton rbSearch;
    @BindView(R.id.iv_clear_input)
    AppCompatImageView ivClearInput;

    @BindView(R.id.sv_progress)
    StepView svProgress;
    @BindView(R.id.fl_bill_step_container)
    FrameLayout flContainer;

    private LRecyclerView rvReturnCart;
    private LinearLayout llEmptyCart;

    private View llToggleReturn;
    private TextView tvActualReturnAmount;
    private Button btnNext;
    private LoadingButton lbReturn;

    // 当前是否正在执行扫码，防止过快扫描
    private boolean isScanExecuted;

    private String mSaleId;
    private String mOrderType;
    private String mOrderCode;
    private boolean isFromList;

    private boolean isReturnSuccess;

    private ADA_BillReturnGoodsList mReturnGoodsAdapter;
    private ADA_BillReturnCartStepOne mReturnCartAdapter;

    private String mMaxReturnAmount;
    private String mShouldReturnAmount;
    private String mActualReturnAmount;

    @Override
    protected void getBundleExtras(Bundle extras) {
        mSaleId = extras.getString(KEY_SALE_ID);
        mOrderType = extras.getString(KEY_ORDER_TYPE);
        mOrderCode = extras.getString(KEY_ORDER_CODE);
        isFromList = extras.getBoolean(KEY_IS_FROM_LIST);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        overridePendingTransition(R.anim.right_in, R.anim.right_out);
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.gravity = Gravity.END;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(params);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        setFinishOnTouchOutside(true);
    }

    @Override
    protected void initEventAndData() {

        initParams();

        initBillGoodsList();

        goFirstStepForReturn();

        initScanCodeRelated();

        mPresenter.initEvent();
        refreshLayout.autoRefresh();
    }


    private void initParams() {

        svProgress.setProgressText("选择退货信息", "确认退货信息", "完成退货");

    }


    private void initScanCodeRelated() {

        GoodsUtil.initScanForGoodsSold(mContext, etScan, etSearchGoods, new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {
                    if (!isScanExecuted) {
                        mPresenter.searchGoodsForReturn(mOrderCode, code);
                    }
                    isScanExecuted = true;
                    etScan.setText("");
                }
                return true;
            }
        }, new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                boolean isInputNotEmpty = !TextUtils.isEmpty(etSearchGoods.getText().toString());
                ivClearInput.setVisibility(isInputNotEmpty ? View.VISIBLE : View.GONE);
                rbSearch.setEnabled(isInputNotEmpty);
                rbSearch.setChecked(isInputNotEmpty);
            }
        });

        etSearchGoods.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, v);

                    String inputStr = etSearchGoods.getText().toString();
                    mPresenter.searchGoodsForReturn(mOrderCode, inputStr);
                }
                return false;
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        etScan.requestFocus();
    }

    private void initBillGoodsList() {

        mReturnGoodsAdapter = new ADA_BillReturnGoodsList(mContext);
        ReturnUtil.initRecyclerView(mContext, rvBillList, mReturnGoodsAdapter, refreshLayout);

        refreshLayout.setOnRefreshListener(new cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mPresenter.searchGoodsForReturn(StringUtils.get(mOrderCode), etSearchGoods.getText().toString());
            }
        });

        ItemClickSupport.addTo(rvBillList)
                .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                        List<ReturnGoodsEntity> goodsList = mReturnGoodsAdapter.getDataList();
                        ReturnGoodsEntity goodsEntity = goodsList.get(position - 1);
                        addGoodsToReturnCart(CloneUtil.clone(goodsEntity), null);
                    }
                });

    }


    private void goFirstStepForReturn() {

        final View stepOneLayout = ReturnUtil.switchReturnStep(mContext, svProgress,
                R.layout.layout_bill_return_step_one, flContainer, mReturnStepList);

        rvReturnCart = stepOneLayout.findViewById(R.id.rv_bill_return);
        mReturnCartAdapter = new ADA_BillReturnCartStepOne(mContext);
        ReturnUtil.initRecyclerView(mContext, rvReturnCart, mReturnCartAdapter, null);
        mReturnCartAdapter.setOnGoodsAmountChangedListener(new ADA_BillReturnCartStepOne.OnGoodsAmountChangedListener() {
            @Override
            public void onAmountChanged(int position) {
                updateSelectCountAndAmount();
                AddReturnCartUtil.updateGoodsSelectStatus(mReturnGoodsAdapter, mReturnCartAdapter);
            }

            @Override
            public void onGoodsDeleted(final int position) {
                showDeleteGoodsDialog(position);
            }
        });

        llEmptyCart = stepOneLayout.findViewById(R.id.ll_empty_cart);
        llToggleReturn = ReturnUtil.initReturnDetailToggle(stepOneLayout);

        stepOneLayout.findViewById(R.id.iv_edit_return_amount)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (ListUtil.isListEmpty(mReturnCartList)) {
                            PosToast.INSTANCE.makeShortToast(mContext, "请选择退货商品~");
                            return;
                        }
                        mPresenter.verifyReturnAuth();
                    }
                });

        btnNext = stepOneLayout.findViewById(R.id.btn_next);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReturnUtil.setLeftLayoutVisible(llRootReturn, llLeft, false);
                goSecondStepForReturn();
            }
        });

        updateCartCountAndPrice(mReturnCartAdapter);

    }

    private void goSecondStepForReturn() {

        View stepTwoLayout = ReturnUtil.switchReturnStep(mContext, svProgress,
                R.layout.layout_bill_return_step_two, flContainer, mReturnStepList);

        LRecyclerView rvConfirmReturnCart = stepTwoLayout.findViewById(R.id.rv_confirm_return);
        ADA_BillReturnCartStepTwo mConfirmReturnAdapter = new ADA_BillReturnCartStepTwo(mContext);
        ReturnUtil.initRecyclerView(mContext, rvConfirmReturnCart, mConfirmReturnAdapter, null);

        llToggleReturn = ReturnUtil.initReturnDetailToggle(stepTwoLayout);

        // 退货商品数量统计
        TextView tvReturnCount = stepTwoLayout.findViewById(R.id.tv_confirm_return_count);
        int returnCount = 0;
        if (!ListUtil.isListEmpty(mReturnCartList)) {
            for (ReturnGoodsEntity entity : mReturnCartList) {
                returnCount += entity.getSelectCount();
            }
        }
        tvReturnCount.setText(String.format("退货商品(%s)", returnCount));

        final TextView tvGoBack = stepTwoLayout.findViewById(R.id.tv_go_back);
        tvGoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReturnUtil.setLeftLayoutVisible(llRootReturn, llLeft, true);
                goFirstStepForReturn();
            }
        });

        lbReturn = stepTwoLayout.findViewById(R.id.lb_do_return);
        lbReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 为退货商品设置最终的退货数量
                if (IsFastClickUtil.isFastClick(v)) {
                    return;
                }
                lbReturn.startLoading("正在退货", ivFinish, tvGoBack);
                for (ReturnGoodsEntity returnGoodsEntity : mReturnCartList) {
                    returnGoodsEntity.setReturnNum(String.valueOf(returnGoodsEntity.getSelectCount()));
                    returnGoodsEntity.setReturnRegisterNum(String.valueOf(returnGoodsEntity.getSelectRegisterCount()));
                }
                String goodsListJson = JSON.toJSONString(mReturnCartList);
                mPresenter.confirmForReturn(goodsListJson, mOrderCode, mActualReturnAmount,
                        String.valueOf(BigDecimalUtil.sub(mShouldReturnAmount, mActualReturnAmount)));
                setFinishOnTouchOutside(false);

            }
        });

        updateCartCountAndPrice(mConfirmReturnAdapter);
    }

    /**
     * 将商品添加到退货购物车
     * <p>
     * 1. 扫码录入或者点击录入时，是单个商品，传入 {@param entity}
     * 一码多物时，有可能是多个商品，传入 {@param list}
     * <p>
     * 2. 具体加入购物车前，调用 {@link AddReturnCartUtil#isGoodEnoughToReturn(List, ReturnGoodsEntity)}
     * 先进行数量判断: 当前待加入的商品数量 + 购物车中现有的商品数量 <= 购买数量
     * 新添加的商品数量都为 1，添加到购物车后自行更改数量
     * <p>
     * 3. 调用 {@link AddReturnCartUtil#updateLocalCartList(LinkedList, List)} 将新添加的商品与本地购物车的数据进行合并
     * 不同商品增加条目，相同商品增加数量；
     * 其中，相同商品增加数量时：
     * 1. 优先增加未寄存商品数量 {@link ReturnGoodsEntity#getSelectUnRegisterCount()}，
     * 2. 加到上限时再去增加寄存商品数量 {@link ReturnGoodsEntity#getSelectRegisterCount()}
     * 3. 左侧商品选中数量  {@link ReturnGoodsEntity#getSelectCount()} 是上面两个属性相加
     * 具体的数量上限检测以及提示语信息在 {@link ADA_BillReturnCartStepOne} 中实现
     * <p>
     * 4. 调用 {@link #updateSelectCountAndAmount()} 变更底部金额信息
     * <p>
     * 5. 调用 {@link AddReturnCartUtil#updateGoodsSelectStatus(CommonAdapter, CommonAdapter)} 变更商品选中情况
     */
    private void addGoodsToReturnCart(ReturnGoodsEntity entity,
                                      List<ReturnGoodsEntity> list) {

        if (entity != null && list != null) {
            throw new RuntimeException("Either entity or list must be null!");
        }

        ArrayList<ReturnGoodsEntity> postList = new ArrayList<>();
        if (entity != null) {
            postList.add(entity);
        } else {
            postList.addAll(list);
        }

        // 配置默认参数
        for (ReturnGoodsEntity goodsEntity : postList) {
            goodsEntity.setSelectCount(1);

            if (!AddReturnCartUtil.isGoodEnoughToReturn(mReturnCartList, goodsEntity)) {
                PosToast.INSTANCE.makeShortToast(mContext, "退货数量不能大于购买数量！");
                return;
            }
        }

        AddReturnCartUtil.updateLocalCartList(mReturnCartList, postList);
        updateCartCountAndPrice(mReturnCartAdapter);
        AddReturnCartUtil.updateGoodsSelectStatus(mReturnGoodsAdapter, mReturnCartAdapter);

    }

    private void updateCartCountAndPrice(CommonAdapter<ReturnGoodsEntity> adapter) {
        adapter.update(mReturnCartList, true);
        updateSelectCountAndAmount();
        showCartListStatus(ListUtil.isListEmpty(mReturnCartList));
    }

    private void showDeleteGoodsDialog(final int position) {
        new PosAlertDialog.Builder(mContext)
                .setRemindText("确认要删除商品吗？")
                .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                    @Override
                    public void onConfirmClick(View view, Dialog dialog) {
                        ReturnGoodsEntity mDeletedEntity
                                = mReturnCartAdapter.getDataList().get(position - 1);
                        mDeletedEntity.setSelectCount(0);
                        mReturnCartList.remove(position - 1);
                        mReturnCartAdapter.getDataList().remove(position - 1);
                        updateSelectCountAndAmount();
                        if (ListUtil.isListEmpty(mReturnCartAdapter.getDataList())) {
                            showCartListStatus(true);
                        }
                        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已删除");
                        AddReturnCartUtil.updateGoodsSelectStatus(mReturnGoodsAdapter, mReturnCartAdapter);
                    }
                }).build().show();
    }

    @Override
    protected int getLayout() {
        return R.layout.act_bill_return;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @OnClick({R.id.iv_finish, R.id.iv_clear_input, R.id.rb_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_finish:
                if (isReturnSuccess) {
                    setResult(Activity.RESULT_OK);
                }
                ReturnUtil.finish(this);
                break;
            case R.id.iv_clear_input:
                etSearchGoods.setText("");
                mPresenter.searchGoodsForReturn(mOrderCode, "");
                etSearchGoods.clearFocus();
                EditTextUtil.hideSoftInput(mContext, etSearchGoods);
                break;
            case R.id.rb_search:
                String inputStr = etSearchGoods.getText().toString();
                mPresenter.searchGoodsForReturn(mOrderCode, inputStr);
                break;

        }
    }

    private void showCartListStatus(boolean isListNull) {
        rvReturnCart.setVisibility(isListNull ? View.GONE : View.VISIBLE);
        llEmptyCart.setVisibility(isListNull ? View.VISIBLE : View.GONE);
        llToggleReturn.setVisibility(isListNull ? View.GONE : View.VISIBLE);
        btnNext.setEnabled(!isListNull);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ReturnUtil.finish(this);
        }
        return super.onKeyUp(keyCode, event);
    }

    private void updateSelectCountAndAmount() {

        TextView tvTotalCount;
        TextView tvTotalPrice;
        TextView tvAvgDiscount;
        TextView tvShouldReturn;

        View layout;
        if (svProgress.getCurrPosition() == 0) {
            layout = mReturnStepList.get(R.layout.layout_bill_return_step_one);
        } else {
            layout = mReturnStepList.get(R.layout.layout_bill_return_step_two);
        }

        tvTotalPrice = layout.findViewById(R.id.tv_total_price);
        tvAvgDiscount = layout.findViewById(R.id.tv_avg_discount);
        tvShouldReturn = layout.findViewById(R.id.tv_should_return);
        tvTotalCount = layout.findViewById(R.id.tv_select_count);
        tvActualReturnAmount = layout.findViewById(R.id.tv_final_return);

        // 选中商品总价
        double selectTotalPrice = 0.0;
        //
        double totalPrice = 0.0;

        for (int i = 0; i < mReturnCartList.size(); i++) {
            ReturnGoodsEntity goodsEntity = mReturnCartList.get(i);

            int goodCount = 0;
            if (goodsEntity.getSelectCount() > goodsEntity.getPresentNum()) {
                goodCount = goodsEntity.getSelectCount() - goodsEntity.getPresentNum();
            }
            double goodPrice = Double.parseDouble(goodsEntity.getRealPay());
            selectTotalPrice += (goodCount * goodPrice);

            totalPrice += goodPrice * (Integer.parseInt(goodsEntity.getGoodsCount()) - goodsEntity.getPresentNum());
        }
        tvTotalPrice.setText("￥" + StringUtils.getFormattedMoney(String.valueOf(selectTotalPrice)));

        // 选中优惠均摊
        double selectTotalDiscount = 0.0;
        double totalDiscount = 0.0;
        for (int i = 0; i < mReturnCartList.size(); i++) {
            ReturnGoodsEntity goodsEntity = mReturnCartList.get(i);

            int goodCount = 0;
            if (goodsEntity.getSelectCount() > goodsEntity.getPresentNum()) {
                goodCount = goodsEntity.getSelectCount() - goodsEntity.getPresentNum();
            }

            double goodDiscount = Double.parseDouble(goodsEntity.getDiscountAvg());
            selectTotalDiscount += (goodCount * goodDiscount);
            totalDiscount += goodDiscount * (Integer.parseInt(goodsEntity.getGoodsCount()) - goodsEntity.getPresentNum());
        }
        tvAvgDiscount.setText("￥" + StringUtils.getFormattedMoney(String.valueOf(selectTotalDiscount)));

        // 设置商品总件数
        int selectCount = 0;
        if (!ListUtil.isListEmpty(mReturnCartList)) {
            for (ReturnGoodsEntity entity : mReturnCartList) {
                selectCount += entity.getSelectCount();
            }
        }
        tvTotalCount.setText(String.valueOf(selectCount));

        // 应退款金额 = 合计 - 优惠均摊
        mShouldReturnAmount = StringUtils.getFormattedMoney(StringUtils.get(selectTotalPrice - selectTotalDiscount));
        tvShouldReturn.setText(String.format("￥%s", mShouldReturnAmount));


        // 实退金额
        // step one，实际退货金额默认与应退金额相同；但是收银员可以编辑
//        if (!mShouldReturnAmount.equals(mActualReturnAmount)) {
//            mActualReturnAmount = mShouldReturnAmount;
//        }

        if (svProgress.getCurrPosition() == 0) {
            mActualReturnAmount = mShouldReturnAmount;
            tvActualReturnAmount.setText(String.format("￥%s", mShouldReturnAmount));
        } else if (svProgress.getCurrPosition() == 1) {
            tvActualReturnAmount.setText(String.format("￥%s", mActualReturnAmount));
        }


    }


    @Override
    public void showReturnGoodsList(List<ReturnGoodsEntity> goodsList) {
        if (StringUtils.isEmpty(etSearchGoods.getText().toString().trim())
                && StringUtils.isEmpty(etScan.getText().toString().trim()) && !isScanExecuted) {
            calculateMaxReturnAmount(goodsList);
        }

        // 停止刷新，并刷新商品列表
        refreshLayout.finishRefresh();
        mReturnGoodsAdapter.update(goodsList, true);
        AddReturnCartUtil.updateGoodsSelectStatus(mReturnGoodsAdapter, mReturnCartAdapter);
        updateSelectCountAndAmount();

        // 如果没有查到内容，说明商品不属于此订单
        if (ListUtil.isListEmpty(goodsList)) {
            PosToast.INSTANCE.makeShortToast(mContext, "您只能选择本账单内的商品~");
            return;
        }

        // 扫码搜索
        if (isScanExecuted) {
            isScanExecuted = false;
            etScan.setText("");

            // 如果只有一个商品，就直接加入购物车；否则展示一码多物的弹窗
            if (goodsList.size() == 1) {
                addGoodsToReturnCart(CloneUtil.clone(goodsList.get(0)), null);
            } else {
                ReturnUtil.showSelectGoodsDialog(mContext, mReturnCartList, goodsList, new ReturnUtil.OnSelectReturnGoodsListener() {
                    @Override
                    public void OnSelectReturnGoodsList(List<ReturnGoodsEntity> list) {
                        addGoodsToReturnCart(null, list);
                    }
                });
            }

        }

    }

    private void calculateMaxReturnAmount(List<ReturnGoodsEntity> goodsList) {

        double totalPrice = 0.0;

        for (int i = 0; i < goodsList.size(); i++) {
            ReturnGoodsEntity goodsEntity = goodsList.get(i);
            double goodPrice = Double.parseDouble(goodsEntity.getRealPay());
            totalPrice += goodPrice * (Integer.parseInt(goodsEntity.getGoodsCount()) - goodsEntity.getPresentNum());
        }
        double totalDiscount = 0.0;
        for (int i = 0; i < goodsList.size(); i++) {
            ReturnGoodsEntity goodsEntity = goodsList.get(i);
            double goodDiscount = Double.parseDouble(goodsEntity.getDiscountAvg());
            totalDiscount += goodDiscount * (Integer.parseInt(goodsEntity.getGoodsCount()) - goodsEntity.getPresentNum());
        }
        //最大可退金额
        mMaxReturnAmount = String.valueOf(BigDecimalUtil.sub(String.valueOf(totalPrice), String.valueOf(totalDiscount)));
    }

    @Override
    public void showError(String msg) {
        super.showError(msg);
        if (isScanExecuted) {
            isScanExecuted = false;
            etScan.setText("");
        }
    }

    @Override
    public void showReturnSuccess(List<ReturnEntity> result) {

        isReturnSuccess = true;
        setFinishOnTouchOutside(true);

        if (lbReturn != null) {
            lbReturn.stopLoading("确认退货");
        }
        if (!ListUtil.isListEmpty(result)) { // 目前不支持组合支付，
            ReturnEntity returnEntity = result.get(0);

            if (!returnEntity.isFlag()) {
                ToastUtil.makeText(mContext, returnEntity.getMsg(), false);
            } else {
                // 所有的旧订单，所有的现金结账，都要弹出钱箱
                if (returnEntity.getPayType().equals(BillUtil.PAY_TYPE_CASH) || returnEntity.getCode() == -1) {
                    PrinterService.openDrawer(mContext);
                } else {
                    for (ReturnEntity entity : result) {
                        if (entity.getPayType().equals(BillUtil.PAY_TYPE_CASH)) {
                            PrinterService.openDrawer(mContext);
                            break;
                        }
                    }
                }

                // 退货成功
                View returnSuccessLayout = ReturnUtil.switchReturnStep(mContext, svProgress,
                        R.layout.layout_bill_return_step_success, flContainer, mReturnStepList);
                svProgress.setVisibility(View.GONE);

                RecyclerView rvReturnMoney = returnSuccessLayout.findViewById(R.id.rv_return_money);
                rvReturnMoney.setLayoutManager(new LinearLayoutManager(mContext));
                rvReturnMoney.setHasFixedSize(true);
                ADA_ReturnMoneyDetail adapter = new ADA_ReturnMoneyDetail(mContext);
                rvReturnMoney.setAdapter(adapter);

                List<PrintPayTypeEntity> payTypeEntities = new ArrayList<>();
                double totalAmount = 0.0;
                for (ReturnEntity entity : result) {
                    PrintPayTypeEntity payTypeEntity = new PrintPayTypeEntity();
                    if (BillUtil.PAY_TYPE_BALANCE.equals(entity.getPayType())) {
                        payTypeEntity.setName("余额退款:");
                    } else if (BillUtil.PAY_TYPE_INTEGRAL.equals(entity.getPayType())) {
                        payTypeEntity.setName(String.format("%s%s退款:", BigDecimalUtil.getNumber(entity.getIntegral()),
                                BillUtil.getSimplePayType(entity.getPayType())));
                    } else {
                        payTypeEntity.setName(String.format("%s退款:", BillUtil.getSimplePayType(entity.getPayType())));
                    }
                    if (!StringUtils.isEmpty(entity.getSysPayCnl()) && entity.getSysPayCnl().equals("1")) {
                        payTypeEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(entity.getMoney()) + "（2个工作日退还）");
                    } else if (entity.getPayType().equals(BillUtil.PAY_TYPE_BANK)) {
                        payTypeEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(entity.getMoney()) + "（请走线下退款）");
                    } else if (entity.getPayType().equals(BillUtil.PAY_TYPE_INTEGRAL)) {
                        payTypeEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(entity.getMoney()) + "（抵现积分不退还）");
                    } else {
                        payTypeEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(entity.getMoney()));
                    }
                    payTypeEntities.add(payTypeEntity);
                    totalAmount = BigDecimalUtil.add(String.valueOf(totalAmount), entity.getMoney());
                }
                PrintPayTypeEntity totalEntity = new PrintPayTypeEntity();
                totalEntity.setName("共退款：");
                totalEntity.setAmount(StringUtils.getFormattedMoneyWithUnit(String.valueOf(totalAmount)));
                payTypeEntities.add(0, totalEntity);
                adapter.update(payTypeEntities);

                TextView tvGoDetail = returnSuccessLayout.findViewById(R.id.tv_go_detail);
                tvGoDetail.setVisibility(isFromList ? View.VISIBLE : View.GONE);
                tvGoDetail.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ACT_BillGoodsDetail.startAct(mContext, mSaleId, Integer.parseInt(mOrderType));
                        setResult(RESULT_FIRST_USER);
                        finish();
                        overridePendingTransition(R.anim.right_in, R.anim.right_out);

                    }
                });

                returnSuccessLayout.findViewById(R.id.tv_done).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setResult(RESULT_OK);
                        finish();
                        overridePendingTransition(R.anim.right_in, R.anim.right_out);
                    }
                });

            }

        } else {
            ToastUtil.makeText(mContext, "退货成功", false);
            setResult(Activity.RESULT_OK);
            ReturnUtil.finish(this);
        }
    }

    @Override
    public void showReturnFailed(String msg) {
        if (lbReturn != null) {
            lbReturn.stopLoading("确认退货");
        }
        final View returnFailLayout = ReturnUtil.switchReturnStep(mContext, svProgress,
                R.layout.layout_bill_return_step_fail, flContainer, mReturnStepList);
        svProgress.setVisibility(View.GONE);

        TextView tvReturnMsg = returnFailLayout.findViewById(R.id.tv_fail_msg);
        tvReturnMsg.setText(msg);

        returnFailLayout.findViewById(R.id.tv_do_not_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReturnUtil.finish(ACT_BillReturn.this);
            }
        });

        returnFailLayout.findViewById(R.id.tv_return_again).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                svProgress.setVisibility(View.VISIBLE);
                ReturnUtil.setLeftLayoutVisible(llRootReturn, llLeft, true);

                mReturnCartList.clear();
                goFirstStepForReturn();
                AddReturnCartUtil.updateGoodsSelectStatus(mReturnGoodsAdapter, mReturnCartAdapter);
            }
        });

    }

    @Override
    public void showUpdateReturnAmount() {
        final AlertDialog updateReturnAmountDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_modify_return_amount)
                .setDialogTitle("修改退货金额")
                .setDialogNoConfirm()
                .setWidth(438)
                .show();
        PosKeyBoardView keyBoardView = updateReturnAmountDialog.findViewById(R.id.keyboard_view);
        EditText etSelectPhone = updateReturnAmountDialog.findViewById(R.id.et_return_amount);
        etSelectPhone.setFocusable(false);
        MoneyFormatUtil.setTextFilter(etSelectPhone);
        keyBoardView.attachTo(etSelectPhone);
        keyBoardView.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {

                if (Double.parseDouble(text) > Double.parseDouble(mMaxReturnAmount)) {
                    PosToast.INSTANCE.makeShortToast(mContext, String.format("最大可退金额为￥%s", mMaxReturnAmount));
                    return;
                }

                mActualReturnAmount = text;
                tvActualReturnAmount.setText(StringUtils.getFormattedMoneyWithUnit(mActualReturnAmount));
                updateReturnAmountDialog.dismiss();
            }
        });
    }

    @Override
    public void goAuthView() {
        ACT_UpReturnMoneyAuth.startAcForResult(this, ACT_UpReturnMoneyAuth.REQUEST_CODE_AUTH);
    }

    @Override
    public void showInventoryError(String msg) {
        if (lbReturn != null) {
            lbReturn.stopLoading("确认退货");
        }

        GoodsUtil.showCheckGoodsInventoryResultDialog(mContext, "以下商品正在盘点，无法退货", msg);
    }

    public static void startActForResult(Activity activity, String saleId, String orderType,
                                         String orderCode, boolean isFromList, int resultCode) {
        Intent intent = new Intent(activity, ACT_BillReturn.class);
        Bundle bundle = new Bundle();
        bundle.putString(KEY_SALE_ID, saleId);
        bundle.putString(KEY_ORDER_TYPE, orderType);
        bundle.putString(KEY_ORDER_CODE, orderCode);
        bundle.putBoolean(KEY_IS_FROM_LIST, isFromList);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, resultCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACT_UpReturnMoneyAuth.REQUEST_CODE_AUTH) {
            if (resultCode == Activity.RESULT_OK) {
                showUpdateReturnAmount();
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 触摸屏幕外关闭 Activity 时，也要回传数据
        if (isReturnSuccess && event.getX() <= 0) {
            setResult(Activity.RESULT_OK);
        }
        return super.onTouchEvent(event);
    }
}
